/*
 * Copyright 2022 The Open Islands Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.openislands.oi.worker.app;

import org.openislands.oi.config.MyNodeInfo;
import org.openislands.oi.constant.RoleType;
import org.openislands.oi.constant.JobState;
import org.openislands.oi.constant.MessageCodeEnum;
import org.openislands.oi.constant.TaskState;
import org.openislands.oi.worker.manager.OfNodeTaskManager;
import org.openislands.oi.worker.manager.TaskManager;
import org.openislands.oi.error.LogicException;
import org.openislands.oi.worker.scheduler.OperatorRuntimeManager;
import org.openislands.oi.pojo.dto.OfNodeTaskDTO;
import org.openislands.oi.pojo.dto.CommonResult;
import org.openislands.oi.pojo.dto.JobDTO;
import org.openislands.oi.pojo.dto.TaskDTO;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class TaskService {
    @Resource
    private TaskManager taskManager;
    @Resource
    private OfNodeTaskManager ofNodeTaskManager;
    @Resource
    private OperatorRuntimeManager runtimeManager;
    @Resource
    private MyNodeInfo myNodeInfo;

    public CommonResult<Boolean> createJob(JobDTO jobDTO) {
        try {
            boolean st = taskManager.createJob(jobDTO);
            return st ? CommonResult.success() : CommonResult.error(MessageCodeEnum.DATA_INSERT_ERROR);
        } catch (LogicException e) {
            return CommonResult.error(e.getResponseMessageCode());
        }
    }

    public CommonResult<Boolean> deleteJob(String jobId) {
        try {
            boolean st = taskManager.deleteJob(jobId);
            return st ? CommonResult.success() : CommonResult.error(MessageCodeEnum.DATA_UPDATE_ERROR);
        } catch (LogicException e) {
            return CommonResult.error(e.getResponseMessageCode(), e.getMessage());
        }
    }

    public CommonResult<JobDTO> queryJob(String jobId) {
        try{
            JobDTO job = taskManager.queryJob(jobId);
            if(job == null){
                return CommonResult.error(MessageCodeEnum.DATA_NOT_FOUND_ERROR, "can not found job");
            }
            return CommonResult.success(job);
        }catch (LogicException e){
            return CommonResult.error(e.getResponseMessageCode(), e.getMessage());
        }
    }

    public CommonResult<Boolean> updateJob(String jobId, JobDTO jobDTO) {
        try{
            boolean st = taskManager.updateJob(jobId, jobDTO);
            return st ? CommonResult.success() : CommonResult.error(MessageCodeEnum.DATA_UPDATE_ERROR);
        }catch (LogicException e){
            return CommonResult.error(e.getResponseMessageCode(), e.getMessage());
        }
    }

    public CommonResult<Boolean> updateJobState(String jobId, JobState jobState) {
        try{
            MessageCodeEnum st = taskManager.updateJobState(jobId, jobState);
            return st == MessageCodeEnum.SUCCESS ? CommonResult.success(): CommonResult.error(st);
        }catch (LogicException e){
            return CommonResult.error(e.getResponseMessageCode(), e.getMessage());
        }
    }

    public CommonResult<Boolean> stopJob(String jobId, JobState toState) {
        try {
            boolean st = taskManager.stopJob(jobId, toState);
            return st ? CommonResult.success() : CommonResult.error(MessageCodeEnum.DATA_UPDATE_ERROR);
        } catch (LogicException e) {
            return CommonResult.error(e.getResponseMessageCode(), e.getMessage());
        }
    }

    public CommonResult<Boolean> createTask(TaskDTO taskDTO) {
        try {
            boolean st = taskManager.createTask(taskDTO);
            return st ? CommonResult.success() : CommonResult.error(MessageCodeEnum.DATA_INSERT_ERROR);
        } catch (LogicException e) {
            return CommonResult.error(e.getResponseMessageCode(), e.getMessage());
        }
    }

    public CommonResult<Boolean> updateTask(String jobId, String taskName, Integer taskVersion, TaskDTO taskDTO) {
        try {
            boolean st = taskManager.updateTask(jobId, taskName, taskVersion, taskDTO);
            return st ? CommonResult.success() : CommonResult.error(MessageCodeEnum.DATA_UPDATE_ERROR);
        } catch (LogicException e) {
            return CommonResult.error(e.getResponseMessageCode(), e.getMessage());
        }
    }

    public CommonResult<Boolean> updateTaskState(String jobId, String taskName, Integer taskVersion, TaskState toState) {
        try {
            MessageCodeEnum st = taskManager.updateTaskState(jobId, taskName, taskVersion, toState);
            return st == MessageCodeEnum.SUCCESS ? CommonResult.success(): CommonResult.error(st);
        } catch (LogicException e) {
            return CommonResult.error(e.getResponseMessageCode(), e.getMessage());
        }
    }

    public CommonResult<OfNodeTaskDTO> startTask(String jobId, String taskName, Integer taskVersion, RoleType role, TaskState toState) {
        try {
            List<OfNodeTaskDTO> ofNodeTasks = ofNodeTaskManager.queryOfNodeTask(jobId, taskName, taskVersion, role, myNodeInfo.getNodeId());
            if (ofNodeTasks.isEmpty()) {
                throw new LogicException(MessageCodeEnum.DATA_NOT_FOUND_ERROR, "can not found task at node");
            } else if (ofNodeTasks.size() > 1) {
                throw new LogicException(MessageCodeEnum.DATA_REDUNDANCY_ERROR, "can not more than one task at the same time");
            }
            OfNodeTaskDTO ofNodeTask = ofNodeTasks.get(0);
            String instance = runtimeManager.launchRuntime(ofNodeTask);
            MessageCodeEnum updateStateSt = ofNodeTaskManager.updateState(jobId, taskName, taskVersion, role, myNodeInfo.getNodeId(), toState);
            if (updateStateSt == MessageCodeEnum.SUCCESS || updateStateSt == MessageCodeEnum.STATE_UPDATE_NOT_EFFECTIVE || updateStateSt == MessageCodeEnum.STATE_TRANSITION_FAILED){
                ofNodeTask.setContainerInstance(instance);
                ofNodeTask.setSubmittedTime(new Date());
                boolean updateOfNodeTaskSt = ofNodeTaskManager.updateOfNodeTask(jobId, taskName, taskVersion, role, myNodeInfo.getNodeId(), ofNodeTask);
            }
            return CommonResult.success(ofNodeTask);
        } catch (LogicException e) {
            return CommonResult.error(e.getResponseMessageCode(), e.getMessage());
        }
    }

    public CommonResult<OfNodeTaskDTO> queryTaskOfNode(String jobId, String taskName, Integer taskVersion, RoleType role) {
        try {
            List<OfNodeTaskDTO> ofNodeTasks = ofNodeTaskManager.queryOfNodeTask(jobId, taskName, taskVersion, role, myNodeInfo.getNodeId());
            if (ofNodeTasks.isEmpty()) {
                throw new LogicException(MessageCodeEnum.DATA_NOT_FOUND_ERROR, "can not found task at node");
            } else if (ofNodeTasks.size() > 1) {
                throw new LogicException(MessageCodeEnum.DATA_REDUNDANCY_ERROR, "can not more than one task at the same time");
            }
            return CommonResult.success(ofNodeTasks.get(0));
        } catch (LogicException e) {
            return CommonResult.error(e.getResponseMessageCode(), e.getMessage());
        }
    }

    public CommonResult<Boolean> activateTask(String jobId, String taskName, Integer taskVersion, RoleType role, TaskState toState) {
        try {
            boolean st = runtimeManager.activateRuntime(jobId, taskName, taskVersion, role, myNodeInfo.getNodeId());
            return st ? CommonResult.success() : CommonResult.error(MessageCodeEnum.DATA_UPDATE_ERROR);
        } catch (LogicException e) {
            return CommonResult.error(e.getResponseMessageCode(), e.getMessage());
        }
    }

    public CommonResult<Boolean> stopTask(String jobId, String taskName, Integer taskVersion, RoleType role, TaskState toState) {
        try {
            boolean st = taskManager.stopTask(jobId, taskName, taskVersion, role, toState);
            return st ? CommonResult.success() : CommonResult.error(MessageCodeEnum.EXECUTION_ERROR);
        } catch (LogicException e) {
            return CommonResult.error(e.getResponseMessageCode(), e.getMessage());
        }
    }
    public CommonResult<Boolean> reportTask(String jobId, String taskName, Integer taskVersion, RoleType role, String nodeId, OfNodeTaskDTO ofNodeTaskDTO) {
        try {
            boolean st = ofNodeTaskManager.updateOfNodeTask(jobId, taskName, taskVersion, role, nodeId, ofNodeTaskDTO);
            return st ? CommonResult.success() : CommonResult.error(MessageCodeEnum.DATA_UPDATE_ERROR);
        } catch (LogicException e) {
            return CommonResult.error(e.getResponseMessageCode(), e.getMessage());
        }
    }
}
